<template>
  <view class="history-container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-left">
         <text class="back-icon" @click="goBack">←</text>
      </view>
      <view class="nav-center">
        <text class="nav-title">历史记录</text>
      </view>
      <view class="nav-right">
        <view class="clear-button" @click="showClearConfirm">
          <text class="clear-icon">🗑️</text>
          <text class="clear-text">清空</text>
        </view>
      </view>
    </view>
   

    <!-- 加载中 -->
    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">正在加载历史记录...</text>
    </view>

    <!-- 历史记录列表 -->
    <view v-else-if="historyList.length > 0" class="history-list">
      <view class="history-item" v-for="(item, index) in historyList" :key="item.id" :class="{ 'history-item-active': activeIndex === index }" @click="activeIndex = index">
        <view class="history-header">
          <text class="history-id">排名: {{ item.rank }}</text>
          <text class="history-date">{{ formatDate(item.createdAt) }}</text>
        </view>
        <view class="history-content">
          <view class="history-info">
            <text class="info-label">模拟结束年龄</text>
            <text class="info-value">{{ item.deathAge }}岁</text>
          </view>
          <view class="history-info">
            <text class="info-label">总储蓄</text>
            <text class="info-value highlight">¥{{ item.score.toFixed(2) }}</text>
          </view>
        </view>
    
      </view>
    </view>

    <!-- 空状态 -->
    <view v-else class="empty-state">
      <view class="empty-icon">📊</view>
      <text class="empty-text">暂无模拟历史记录</text>
      <text class="empty-hint">完成模拟后将显示在这里</text>
      <view class="empty-action" @click="goToSimulator">
        <text class="action-text">开始模拟</text>
      </view>
    </view>
  </view>
</template>

<script>
import apiConfig from '@/config/api.js'
export default {
  data() {
    return {
      loading: true,
      historyList: [],
      activeIndex: -1
    };
  },
  onLoad() {
    // 页面加载时获取历史记录数据
    this.fetchHistoryData();
  },
  methods: {
    // 返回上一页
    goBack() {
      uni.redirectTo({ url: '/pages/simulator/index' });
    },
    
    // 显示清空确认对话框
    showClearConfirm() {
      uni.showModal({
        title: '确认清空',
        content: '确定要清空所有历史记录吗？此操作不可恢复。',
        confirmText: '确定清空',
        confirmColor: '#f56c6c',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            this.clearHistory();
          }
        }
      });
    },
    
    // 清空历史记录
    async clearHistory() {
      try {
        // 调用后端API清空历史记录
        const token = uni.getStorageSync('token');
        const response = await uni.request({
          url: `${apiConfig.baseUrl}/api/simulator/history/clear`,
          method: 'DELETE',
          header: {
            'content-type': 'application/json',
            'Authorization': 'Bearer ' + token
          }
        });
        
        if (response.data.code === 200) {
          // 清空本地数据
          this.historyList = [];
          
          // 显示成功提示
          uni.showToast({
            title: '历史记录已清空',
            icon: 'success',
            duration: 2000
          });
        } else {
          throw new Error(response.data.message);
        }
      } catch (error) {
        console.error('清空历史记录失败:', error);
        uni.showToast({
          title: '清空历史记录失败',
          icon: 'none',
          duration: 2000
        });
      }
    },

    // 导航到模拟器页面
    goToSimulator() {
      uni.navigateTo({
        url: '/pages/simulator/risk-select'
      });
    },

    // 格式化日期
    formatDate(timestamp) {
      // 处理API返回的ISO格式日期 "2023-06-01T10:00:00"
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },

    // 获取历史记录数据
    async fetchHistoryData() {
      this.loading = true;
      try {
        // 调用后端API获取历史记录
        const token = uni.getStorageSync('token');
        const response = await uni.request({
          url: `${apiConfig.baseUrl}/api/simulator/history`,
          method: 'GET',
          header: {
            'content-type': 'application/json',
            'Authorization': 'Bearer ' + token
          }
        });
        
        // 处理API响应
        if (response.data.code === 200) {
          this.historyList = response.data.data || [];
        } else {
          throw new Error(response.data.message);
        }
      } catch (error) {
        console.error('获取历史记录失败:', error);
        uni.showToast({
          title: '获取历史记录失败',
          icon: 'none'
        });
        
        // 出错时清空列表
        this.historyList = [];
      } finally {
        this.loading = false;
      }
    },
    
    // 从后端获取历史记录的方法
    async getHistoryFromBackend() {
      try {
        // 调用后端API获取历史记录
        const response = await uni.request({
          url: `${apiConfig.baseUrl}/api/simulator/history`,
          method: 'GET',
          header: {
            'content-type': 'application/json'
          }
        });
        
        // 处理API响应
        if (response.statusCode === 200 && response.data) {
          return {
            historyList: response.data.historyList || []
          };
        } else {
          console.error('API响应错误:', response);
          // 在API返回错误时，使用模拟数据
          return {
            historyList: this.generateMockHistory()
          };
        }
      } catch (error) {
        console.error('获取历史记录API调用失败:', error);
        // 在发生异常时，使用模拟数据
        return {
          historyList: this.generateMockHistory()
        };
      }
    },
    
    // 生成模拟历史记录数据
    generateMockHistory() {
      const history = [];
      const now = Date.now();
      
      // 生成6条模拟历史记录
      for (let i = 0; i < 6; i++) {
        // 模拟不同的结束年龄（60-70岁）
        const endAge = 60 + Math.floor(Math.random() * 11);
        // 模拟不同的总储蓄金额
        const savings = Math.floor(50000 + Math.random() * 950000);
        // 模拟不同的时间戳（最近30天内）
        const timestamp = now - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000;
        
        history.push({
          id: `REC${String(1000 + i).slice(-4)}`,
          userId: 'USER12345',
          rank: i + 1, // 添加排名，从1开始
          endAge: endAge,
          totalSavings: savings,
          timestamp: timestamp
        });
      }
      
      // 按时间倒序排列（最新的在前面）
      return history.sort((a, b) => b.timestamp - a.timestamp)
        // 根据总储蓄金额添加排名
        .sort((a, b) => b.totalSavings - a.totalSavings)
        .map((item, index) => ({
          ...item,
          rank: index + 1 // 根据排序后的顺序重新设置排名
        }));
    },
    
    // 设置模拟数据（在API调用失败时使用）
    setMockData() {
      this.historyList = this.generateMockHistory();
    }
  }
};
</script>

<style scoped>
/* 主容器 */
.history-container {
  position: relative;
  min-height: 100vh;
  background: linear-gradient(to bottom, #e6f7ff 0%, #ffffff 100%);
  background-size: 100% 100%;
  padding-bottom: 40rpx;
  color: #333;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  line-height: 1.5;
}

/* 顶部导航栏 */
.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 40rpx 30rpx 20rpx 0;
  margin: 1rpx 1rpx;
  background-color: #e6f7ff;
  border-radius: 20rpx;
  backdrop-filter: blur(10rpx);
}

.nav-left {
  width: 150rpx;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-left: 50rpx;
  padding-left: 20rpx;
}

.nav-right {
  width: 150rpx;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

/* 清空按钮样式 */
.clear-button {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10rpx 20rpx;
  border-radius: 40rpx;
  background: linear-gradient(135deg, rgba(245, 108, 108, 0.1) 0%, rgba(245, 108, 108, 0.05) 100%);
  border: 2rpx solid rgba(245, 108, 108, 0.2);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.clear-button::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 0;
  height: 100%;
  background: rgba(245, 108, 108, 0.1);
  border-radius: 50%;
  transform: translate(-50%, -50%);
  transition: width 0.6s ease;
}

.clear-button:active::before {
  width: 300rpx;
}

.clear-button:active {
  transform: scale(0.95);
  background: linear-gradient(135deg, rgba(245, 108, 108, 0.2) 0%, rgba(245, 108, 108, 0.1) 100%);
  border-color: rgba(245, 108, 108, 0.3);
}

.clear-icon {
  font-size: 32rpx;
  margin-right: 8rpx;
  opacity: 0.8;
}

.clear-text {
  font-size: 28rpx;
  color: #f56c6c;
  font-weight: 500;
}

/* 返回按钮 */
.back-icon {
  font-size: 65rpx;
  color: #4facfe;
  font-weight: bold;
  transition: all 0.3s ease;
  position: relative;
  z-index: 1;
  margin-left: 0;
  padding-left: 0;
}

.back-icon::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 60rpx;
  height: 60rpx;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  transform: translate(-50%, -50%) scale(0);
  transition: transform 0.3s ease;
  z-index: -1;
}

.back-icon:active {
  transform: scale(0.9);
}

.back-icon:active::after {
  transform: translate(-50%, -50%) scale(1);
}


.nav-title {
  display: block;
  font-size: 45rpx;
  font-weight: 700;
  color: #333;
  margin-bottom: 0rpx;
  text-align: center;
  text-align: center;
}

/* 加载中样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 500rpx;
  gap: 40rpx;
}

/* 旋转加载图标 */
.loading-spinner {
  width: 80rpx;
  height: 80rpx;
  border: 8rpx solid rgba(255, 255, 255, 0.3);
  border-top: 8rpx solid #FFF;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  box-shadow: 0 0 30rpx rgba(255, 255, 255, 0.3);
}

/* 加载文字 */
.loading-text {
  font-size: 32rpx;
  color: #4facfe;
  font-weight: 600;
  animation: pulse 1.5s ease-in-out infinite;
}

/* 旋转动画 */
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 脉冲动画 */
@keyframes pulse {
  0%, 100% { opacity: 1; transform: scale(1); }
  50% { opacity: 0.8; transform: scale(1.05); }
}

/* 历史记录列表 */
.history-list {
  padding: 30rpx;
  margin-top: 20rpx;
}

/* 历史记录项 */
.history-item {
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 25rpx;
  padding: 25rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  border-left: 10rpx solid #ffffff;
}

.history-item:active,
.history-item-active {
  transform: translateY(-5rpx);
  box-shadow: 0 12rpx 30rpx rgba(0, 0, 0, 0.15);
  background-color: rgba(255, 255, 255, 0.95);
}

/* 历史记录头部 */
.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding-bottom: 15rpx;
  border-bottom: 1rpx solid rgba(0, 0, 0, 0.1);
}

.history-id {
  font-size: 28rpx;
  font-weight: 600;
  color: #667eea;
}

.history-date {
  font-size: 24rpx;
  color: #999;
}

/* 历史记录内容 */
.history-content {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.history-info {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.info-label {
  font-size: 30rpx;
  color: #666;
}

.info-value {
  font-size: 38rpx;
  font-weight: 700;
  color: #333;
}

.info-value.highlight {
  color: #4facfe;
  background: linear-gradient(135deg, #4facfe, #00f2fe);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

/* 历史记录底部 */
.history-footer {
  text-align: right;
}

.history-index {
  font-size: 22rpx;
  color: #999;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 500rpx;
  gap: 30rpx;
  padding: 40rpx;
  text-align: center;
  opacity: 0;
  animation: fadeIn 0.6s ease-out forwards;
}

.empty-icon {
  font-size: 120rpx;
  animation: bounce 2s ease-in-out infinite;
}

.empty-text {
  font-size: 34rpx;
  font-weight: 600;
  color: #4facfe;
  margin-bottom: 10rpx;
}

.empty-hint {
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
}

.empty-action {
  margin-top: 20rpx;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  padding: 15rpx 60rpx;
  border-radius: 40rpx;
  box-shadow: 0 10rpx 30rpx rgba(79, 172, 254, 0.4);
  transition: all 0.3s ease;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.empty-action:active {
  transform: scale(0.95);
  box-shadow: 0 5rpx 20rpx rgba(102, 126, 234, 0.3);
}

.action-text {
  font-size: 28rpx;
  font-weight: 600;
  color: #FFF;
}

/* 淡入动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 弹跳动画 */
@keyframes bounce {
  0%, 20%, 50%, 80%, 100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-20rpx);
  }
  60% {
    transform: translateY(-10rpx);
  }
}
</style>